package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.SystemConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    private final StringRedisTemplate stringRedisTemplate;

    private final CacheClient cacheClient;

    @Override
    public Result<Shop> queryById(Long id) {
        //缓存穿透
//        Shop shop = cacheClient.queryWithPassThrough(
//                CACHE_SHOP_KEY, id,
//                Shop.class, CACHE_SHOP_TTL, TimeUnit.MINUTES,
//                this::getById
//        );
//        Shop shop = queryWithMutex(id);
        //缓存击穿
        Shop shop = cacheClient.queryWithLogicalExpire(
                CACHE_SHOP_KEY,id,
                Shop.class,this::getById,
                CACHE_SHOP_TTL,TimeUnit.MINUTES);

        if (shop == null) {
            return Result.fail("店铺不存在");
        }
        //返回
        return Result.ok(shop);
    }

//
//    /**
//     * 缓存击穿
//     * 缓存击穿是缓存和数据库中都存在某个数据，但是由于缓存和数据库的数据不一致，导致缓存击穿。
//     * @param id
//     * @return
//     */
/*    public Shop queryWithMutex(Long id){
        String key=CACHE_SHOP_KEY+id;
        //尝试从redis中查询缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //判断是否存在
        if(StrUtil.isNotBlank(shopJson)){
            //存在直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //命中是否是“”值
        if(shopJson!=null){
            return null;
        }
        //实现缓存重建
        //获取互斥锁
        String lock = LOCK_SHOP_KEY+id;
        Shop shop = null;
        try {
            boolean isLock = tryLock(lock);
            //判断是否获取成功
            if(!isLock){
                //失败休眠
                 Thread.sleep(50);
                 return queryWithMutex(id);//重新获取
            }
            //成功获取到锁查询数据库
            //不存在，从数据库中查询，
            shop = getById(id);
            //模拟重建时的延时
            Thread.sleep(200);
            //不存在返回错误
            if(shop==null){
                stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
                return null;
            }
            //存在 ，存入redis ，设置超时时间
            shopJson = JSONUtil.toJsonStr(shop);
            stringRedisTemplate.opsForValue().set(key,shopJson,CACHE_SHOP_TTL + RandomUtil.randomLong(5), TimeUnit.MINUTES);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            unLock(lock);
        }
        //返回
        return shop;
    }*/


/*
    public void saveShop2Redis(Long id, Long expireSeconds) throws InterruptedException {
        //1.查询店铺数据
        Shop shop = getById(id);
        Thread.sleep(200);
        //2.封装逻辑过期时间
        RedisData redisData=new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));

        //3.写入redis
        String jsonStr = JSONUtil.toJsonStr(redisData);
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,jsonStr);
    }
*/

    @Override
    @Transactional
    public Result update(Shop shop) {
        if (shop.getId()==null){
            return Result.fail("商铺id不能为空");
        }
        //更新数据库
        updateById(shop);
        //删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY+shop.getId());
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //是否需要根据坐标查询
        if(x==null||y==null){
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        //计算分页参数
        int from = (current-1)*SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current*SystemConstants.DEFAULT_PAGE_SIZE;
        //查询redis 按照距离排序、分页、  返回结果 shopId distance(距离)
        String key=SHOP_GEO_KEY+typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> search = stringRedisTemplate.opsForGeo().search(
                key,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
        );
        if(search==null){
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> lists = search.getContent();
        if(lists.size()<=from){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids=new ArrayList<>();
        Map<String,Distance> map=new HashMap<>();
        lists.stream().skip(from).forEach(new Consumer<GeoResult<RedisGeoCommands.GeoLocation<String>>>() {
            @Override
            public void accept(GeoResult<RedisGeoCommands.GeoLocation<String>> list) {
                String shopId = list.getContent().getName();
                Distance distance = list.getDistance();
                map.put(shopId,distance);
                ids.add(Long.valueOf(shopId));
            }
        });
        List<Shop> listShop = query().in("id", ids).last("order by field(id," + StrUtil.join(",", ids) + ")").list();
        for (Shop shop : listShop) {
            shop.setDistance(map.get(shop.getId().toString()).getValue());
        }
        return Result.ok(listShop);
    }

}
